package com.shiku.mianshi.controller;

import cn.xyz.commons.constants.KConstants;
import cn.xyz.commons.ex.ServiceException;
import cn.xyz.commons.utils.ReqUtil;
import cn.xyz.commons.vo.JSONMessage;
import cn.xyz.mianshi.model.PageResult;
import cn.xyz.mianshi.model.PageVO;
import cn.xyz.mianshi.utils.SKBeanUtils;
import cn.xyz.mianshi.vo.*;

import com.wxpay.utils.WXNotify;
import com.wxpay.utils.WXPayUtil;
import com.wxpay.utils.WxPayResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import java.util.List;
@RestController
@Api(value="ConsumeRecordController",tags="消费记录接口")
@RequestMapping(value = "",method = {RequestMethod.POST,RequestMethod.GET})
public class ConsumeRecordController extends AbstractController {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@ApiOperation("用户充值记录列表")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType="query" , name="pageIndex" , value="当前页码数",dataType="int"),
			@ApiImplicitParam(paramType="query" , name="pageSize" , value="每页数据条数",dataType="int",defaultValue="10")
	})
	@RequestMapping("/user/recharge/list")
	public JSONMessage getList(@RequestParam(defaultValue="0")int pageIndex,@RequestParam(defaultValue="10")int pageSize) {
		Object data = SKBeanUtils.getConsumeRecordManager().reChargeList(ReqUtil.getUserId(), pageIndex, pageSize);
		return JSONMessage.success(data);
	}
	

	@ApiOperation("用户消费记录列表 ")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType="query" , name="pageIndex" , value="当前页码数",dataType="int"),
			@ApiImplicitParam(paramType="query" , name="pageSize" , value="每页数据条数",dataType="int",defaultValue = "10"),
			@ApiImplicitParam(paramType="query" , name="startTime" , value="查询开始月份(如查六月份开始数据，传 2020-07-01 00:00 的时间戳,不传数据表示从当前开始)",dataType="int",defaultValue = "-1"),
			@ApiImplicitParam(paramType="query" , name="queryType" , value="查询类型(不传，或-1 为查询全部)",dataType="int",defaultValue = "-1")
	})
	@RequestMapping("/user/consumeRecord/list")
	public JSONMessage consumeRecordList(@RequestParam(defaultValue="0")int pageIndex,@RequestParam(defaultValue="10")int pageSize,@RequestParam(defaultValue="-1")int startTime,
			@RequestParam(defaultValue="-1")int queryType) throws ParseException {
		try {
			PageResult<ConsumeRecord> result = SKBeanUtils.getConsumeRecordManager().consumeRecordList(ReqUtil.getUserId(), pageIndex, pageSize,(byte)0,startTime,queryType);
			  PageResult<ConsumeRecordV2> resultData =new PageResult<ConsumeRecordV2>();
			  List<ConsumeRecordV2> _returnBuffer = new ArrayList();
			  resultData.setData(_returnBuffer);
			 long _startTimes_ts = 0;
			 long _startTimes_ts_ex = 0;
			 ConsumeRecordV2 _monthData = null;
			
			    for(int i=0;i<result.getData().size();i++)
			    {
			    	if(i==0 || _startTimes_ts_ex > result.getData().get(i).getTime())
			    	{
			    		if(_monthData != null)
			    		{
			    			resultData.getData().add(_monthData);
			    		}
			    		  _monthData = new ConsumeRecordV2();
						 List<ConsumeRecord> _bufferData = new ArrayList();
						 _monthData.setData(_bufferData);
			    		//取得统计的时间范围
			    		Calendar _calendar1 = Calendar.getInstance();
						_calendar1.setTimeInMillis(result.getData().get(i).getTime()*1000);
			    		String _szStartTimes = _calendar1.get(Calendar.YEAR)+"-"+(_calendar1.get(Calendar.MONTH)+2)+"-01 00:00:00";
			    		 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			    		 Date date = simpleDateFormat.parse(_szStartTimes);
					     _startTimes_ts = date.getTime();
					    
					    _calendar1.setTimeInMillis(_startTimes_ts);
					    long endTimes= _calendar1.getTime().getTime()/1000;
					    
					    _calendar1.add(Calendar.MONTH, -1);
					    long startTimes= _calendar1.getTime().getTime()/1000;
					    _startTimes_ts_ex = startTimes;
					    ConsumeTotal _data =  SKBeanUtils.getConsumeRecordManager().GetConsumeTotal(ReqUtil.getUserId(),startTimes,endTimes,queryType);
					    String _MONTH ="0" + (_calendar1.get(Calendar.MONTH)+1);
					    _MONTH = _MONTH.substring(_MONTH.length() -2,_MONTH.length());
					    _monthData.setMonth(_calendar1.get(Calendar.YEAR)+"-"+_MONTH);
					    
					    DecimalFormat decimalFormat=new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
						String  szIncomeTotal= decimalFormat.format(_data.getTotalTecharge()+_data.getTotalAccount()+_data.getReceivePacket());//format 返回的是字符串
						
						DecimalFormat decimalFormat2=new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
					    String szExpendTotal = decimalFormat2.format(_data.getTotalTransfer()+_data.getSendPacket()+_data.getTotalCash());
						_monthData.setIncomeTotal(szIncomeTotal);
					    _monthData.setExpendTotal(szExpendTotal);
			    	}
			    	_monthData.getData().add(result.getData().get(i));
			    	
			    }
			    if(result.getData().size() == 0)
			    {
			    	  _monthData = new ConsumeRecordV2();
			    	  Calendar _calendar1 = Calendar.getInstance();
			    	  if(startTime<0)
			    	  {
			    		
							_calendar1.setTimeInMillis(System.currentTimeMillis());
			    	  }
			    	  else {
			    		  	long mTimes = (long)startTime*1000-1;
			    		  _calendar1.setTimeInMillis(mTimes);
			    		 
			    	  }
			    	  String _MONTH ="0" + (_calendar1.get(Calendar.MONTH)+1);
					    _MONTH = _MONTH.substring(_MONTH.length() -2,_MONTH.length());
			    	  
			    	  _monthData.setMonth(_calendar1.get(Calendar.YEAR)+"-"+_MONTH);
					    _monthData.setIncomeTotal("0");
					    _monthData.setExpendTotal("0");
					    
						 List<ConsumeRecord> _bufferData = new ArrayList();
						 _monthData.setData(_bufferData);
			    }
			    resultData.getData().add(_monthData);
			    	
			PageVO data = new PageVO(resultData.getData(),result.getCount(),pageIndex,pageSize);
			return JSONMessage.success(data);
		} catch (ServiceException e) {
			return JSONMessage.failureByException(e);
		}
		
	}


	@RequestMapping("/user/digitalConsumeRecord/list")
	public JSONMessage consumeRecordListEx(@RequestParam(defaultValue="0")int pageIndex,@RequestParam(defaultValue="10")int pageSize,@RequestParam(defaultValue="-1")int startTime,
										 @RequestParam(defaultValue="-1")int queryType) throws ParseException {
		try {
			PageResult<DigitalConsumeRecord> result = SKBeanUtils.getConsumeRecordManager().digitalConsumeRecordList(ReqUtil.getUserId(), pageIndex, pageSize,(byte)0,startTime,queryType);
			PageResult<ConsumeRecordV3> resultData =new PageResult<ConsumeRecordV3>();
			List<ConsumeRecordV3> _returnBuffer = new ArrayList();
			resultData.setData(_returnBuffer);
			long _startTimes_ts = 0;
			long _startTimes_ts_ex = 0;
			ConsumeRecordV3 _monthData = null;

			for(int i=0;i<result.getData().size();i++)
			{
				if(i==0 || _startTimes_ts_ex > result.getData().get(i).getTime())
				{
					if(_monthData != null)
					{
						resultData.getData().add(_monthData);
					}
					_monthData = new ConsumeRecordV3();
					List<DigitalConsumeRecord> _bufferData = new ArrayList();
					_monthData.setData(_bufferData);
					//取得统计的时间范围
					Calendar _calendar1 = Calendar.getInstance();
					_calendar1.setTimeInMillis(result.getData().get(i).getTime()*1000);
					String _szStartTimes = _calendar1.get(Calendar.YEAR)+"-"+(_calendar1.get(Calendar.MONTH)+2)+"-01 00:00:00";
					SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					Date date = simpleDateFormat.parse(_szStartTimes);
					_startTimes_ts = date.getTime();

					_calendar1.setTimeInMillis(_startTimes_ts);
					long endTimes= _calendar1.getTime().getTime()/1000;

					_calendar1.add(Calendar.MONTH, -1);
					long startTimes= _calendar1.getTime().getTime()/1000;
					_startTimes_ts_ex = startTimes;
					ConsumeTotal _data =  SKBeanUtils.getConsumeRecordManager().GetConsumeTotalEx(ReqUtil.getUserId(),startTimes,endTimes,queryType);
					String _MONTH ="0" + (_calendar1.get(Calendar.MONTH)+1);
					_MONTH = _MONTH.substring(_MONTH.length() -2,_MONTH.length());
					_monthData.setMonth(_calendar1.get(Calendar.YEAR)+"-"+_MONTH);

					DecimalFormat decimalFormat=new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
					String  szIncomeTotal= decimalFormat.format(_data.getTotalTecharge()+_data.getTotalAccount()+_data.getReceivePacket());//format 返回的是字符串

					DecimalFormat decimalFormat2=new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
					String szExpendTotal = decimalFormat2.format(_data.getTotalTransfer()+_data.getSendPacket()+_data.getTotalCash());
					_monthData.setIncomeTotal(szIncomeTotal);
					_monthData.setExpendTotal(szExpendTotal);
				}
				_monthData.getData().add(result.getData().get(i));

			}
			if(result.getData().size() == 0)
			{
				_monthData = new ConsumeRecordV3();
				Calendar _calendar1 = Calendar.getInstance();
				if(startTime<0)
				{

					_calendar1.setTimeInMillis(System.currentTimeMillis());
				}
				else {
					long mTimes = (long)startTime*1000-1;
					_calendar1.setTimeInMillis(mTimes);

				}
				String _MONTH ="0" + (_calendar1.get(Calendar.MONTH)+1);
				_MONTH = _MONTH.substring(_MONTH.length() -2,_MONTH.length());

				_monthData.setMonth(_calendar1.get(Calendar.YEAR)+"-"+_MONTH);
				_monthData.setIncomeTotal("0");
				_monthData.setExpendTotal("0");

				List<DigitalConsumeRecord> _bufferData = new ArrayList();
				_monthData.setData(_bufferData);
			}
			resultData.getData().add(_monthData);

			PageVO data = new PageVO(resultData.getData(),result.getCount(),pageIndex,pageSize);
			return JSONMessage.success(data);
		} catch (ServiceException e) {
			return JSONMessage.failureByException(e);
		}

	}

	@ApiOperation("消费列表")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType="query" , name="pageIndex" , value="当前页码数",dataType="int",defaultValue = "0"),
			@ApiImplicitParam(paramType="query" , name="pageSize" , value="每页数据条数",dataType="int",defaultValue = "10"),
			@ApiImplicitParam(paramType="query" , name="toUserId" , value="发送方编号",dataType="int",defaultValue = "0")
	})
	@RequestMapping("/friend/consumeRecordList")
	public JSONMessage friendRecordList(@RequestParam(defaultValue="0")int toUserId,@RequestParam(defaultValue="0")int pageIndex,@RequestParam(defaultValue="10")int pageSize) {
		try {
			PageResult<ConsumeRecord> result = SKBeanUtils.getConsumeRecordManager()
					.friendRecordList(ReqUtil.getUserId(),toUserId, pageIndex, pageSize,(byte)0);
			if(0==result.getCount())
				return JSONMessage.success(null, null);
			PageVO data = new PageVO(result.getData(),result.getCount(),pageIndex,pageSize);
			return JSONMessage.success(data);
		} catch (ServiceException e) {
			return JSONMessage.failureByException(e);
		}
		
	}
	
	

	@ApiOperation("删除消费记录 ")
	@ApiImplicitParam(paramType="query" , name="id" , value="记录Id",dataType="String",required=true)
	@RequestMapping("/recharge/delete")
	public JSONMessage delete(String id) {
		Object data = SKBeanUtils.getConsumeRecordManager().getConsumeReCord(ReqUtil.getUserId(),new ObjectId(id));
		if(null != data){
			SKBeanUtils.getConsumeRecordManager().deleteById(ReqUtil.parseId(id));
			return JSONMessage.success();
		}else{
			return JSONMessage.failure(null);
		}
	}
	
	@ApiOperation("微信支付回调数据")
	@RequestMapping(value="/user/recharge/wxPayCallBack")
	public void wxPayCallBack(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		//把如下代码贴到的你的处理回调的servlet 或者.do 中即可明白回调操作
		logger.info("微信支付回调数据开始");
		BufferedOutputStream out = null;
		String inputLine;
		String notityXml = "";
		String resXml = "";
		try {
			while ((inputLine = request.getReader().readLine()) != null) {
				notityXml += inputLine;
			}
			request.getReader().close();
			
			Map<String,String> m = WXNotify.parseXmlToList2(notityXml);
			logger.info("接收到的报文：" + m);
				String tradeNo=m.get("out_trade_no");
				ConsumeRecord entity=SKBeanUtils.getConsumeRecordManager().getConsumeRecordByNo(tradeNo);
				if(null==entity)
					logger.info("交易订单号不存在！-----"+tradeNo);
				else if(0!=entity.getStatus())
					logger.info(tradeNo+"===status==="+entity.getStatus()+"=======交易已处理或已取消!");
				else if("SUCCESS".equals(m.get("result_code"))){
					boolean flag=Double.valueOf(m.get("cash_fee"))==entity.getMoney()*100;
					if(flag){
						 //logger.info("支付金额比较"+m.get("cash_fee")+"=="+entity.getMoney()*100+"=======>"+flag);
						WxPayResult wpr = WXPayUtil.mapToWxPayResult(m);
						//支付成功
						resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
						+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
						entity.setStatus(KConstants.OrderStatus.END);
						if( entity.getMoney()<0){
							throw new ServiceException(KConstants.PayResultCode.InsufficientBalance);
						}
						Double balance = SKBeanUtils.getUserManager().rechargeUserMoeny(entity.getUserId(), entity.getMoney(), KConstants.MOENY_ADD);
						entity.setOperationAmount(entity.getMoney());
						entity.setCurrentBalance(balance);
						SKBeanUtils.getConsumeRecordManager().update(entity.getId(), entity);
						SKBeanUtils.getConsumeRecordManager().saveEntity(wpr);
						logger.info(tradeNo+"========>>微信支付成功!");
					}else{
						logger.info("微信数据返回错误!");
						logger.info("localhost:Money---------"+entity.getMoney()*100);
						logger.info("Wxpay:Cash_fee---------"+m.get("cash_fee"));
					}
				}else{
					logger.info("微信支付失败======"+m.get("return_msg"));
					resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
					+ "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
				}
				out = new BufferedOutputStream(response.getOutputStream());
				out.write(resXml.getBytes());
				out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if (out != null)
				out.close();
		}
		
	}

}
